#pragma once
#include<iostream>
#include<memory>
#include<functional>
#include"TcpServer.hpp"
#include<unistd.h>
class TcpServer;
class Connection
{
public:
    using func_t=std::function<void(Connection*)>;
    Connection(int sockfd,uint32_t event,TcpServer* R):_fd(sockfd),_event(event),_R(R){}
    int GetFd()
    {
        return _fd;
    }
    uint32_t GetEvent()
    {
        return _event;
    }
    void RegisterCallback(func_t recver,func_t sender,func_t excepter)
    {
        _recver=recver;
        _sender=sender;
        _excepter=excepter;
    }
    void AddInbuffer(const std::string& in)
    {
        in_buffer+=in;
    }
    std::string& GetInbuffer()
    {
        return in_buffer;
    }
    std::string& GetOutbuffer()
    {
        return out_buffer;
    }
    void AddOutbuffer(const std::string& out)
    {
        out_buffer+=out;
    }
    bool IsEmptyOutbuffer()
    {
        return out_buffer.empty();
    }
    void SetEvent(uint32_t event)
    {
        _event=event;
    }
    void Close()
    {
        close(_fd);
    }
    ~Connection()
    {
        
    }
private:
    int _fd;
    std::string in_buffer;
    std::string out_buffer;
    uint16_t _port;
    uint32_t _event;
public:
    func_t _recver;
    func_t _sender;
    func_t _excepter;
    TcpServer* _R;
};


class ConnectionFactory
{
public:
    static Connection* BuildListenConnection(int listensock,Connection::func_t recver,uint32_t event,TcpServer*R)
    {
        Connection* conn=new Connection(listensock,event,R);
        conn->RegisterCallback(recver,nullptr,nullptr);
        return conn;
    }
    static Connection *BuildNormalConnection(int sock, Connection::func_t recver,
                                             Connection::func_t sender, Connection::func_t excepter, 
                                             uint32_t event, TcpServer *R)
    {
        Connection*conn =new Connection(sock,event,R);
        conn->RegisterCallback(recver,sender,excepter);
        return conn;
    }
};